<template>
  <uni-forms
    ref="myForm"
    :label-width="100"
    label-align="right"
    :modelValue="model"
    :rules="rules"
  >
    <uni-forms-item label="交易类型" required name="type">
      <radio-group @change="onTypeChange">
        <label v-for="option in typeOptions" :key="option.value">
          <radio
            :value="option.value"
            :checked="option.value === model.type"
          ></radio>
          {{ option.text }}
        </label>
      </radio-group>
    </uni-forms-item>

    <uni-forms-item label="交易地址" required name="address">
      <input v-model="model.address" disabled @click="onChooseLocation" />
    </uni-forms-item>

    <uni-forms-item label="交易描述" required name="message">
      <input v-model="model.message" />
    </uni-forms-item>

    <uni-forms-item label="联系方式" required name="contact">
      <input v-model="model.contact" maxlength="11" />
    </uni-forms-item>
  </uni-forms>

  <button @click="handleConfirm">确认</button>
</template>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";

const { ctx } = getCurrentInstance() as any;

/** 交易类型选项 */
const typeOptions = [
  { value: "buy", text: "买" },
  { value: "sell", text: "卖" },
];

// 用于表单实例
const myForm = ref();

// 表单数据
const model = reactive({
  id: -1,
  address: "",
  lat: 0,
  lng: 0,
  message: "",
  contact: "",
  type: "buy",
});

// 校验规则
const rules = {
  address: {
    rules: [{ required: true, errorMessage: "交易地址不能为空" }],
  },

  type: {
    rules: [{ required: true, errorMessage: "交易类型不能为空" }],
  },

  message: {
    rules: [{ required: true, errorMessage: "交易描述不能为空" }],
  },

  contact: {
    rules: [
      { required: true, errorMessage: "联系方式不能为空" },
      {
        pattern: /^1\d{10}$/,
        errorMessage: "联系方式不正确",
      },
    ],
  },
};

/** 交易类型选择 */
const onTypeChange = (event: any) => {
  // console.log("onTypeChange", event);
  // 1. 获取当前勾选的 Radio 的 value
  const { value } = event.detail;
  // 2. 将 value 赋值给 model.type
  model.type = value;
};

/** 获取数据 */
const refresh = async (id: string) => {
  uni.showLoading({ title: "加载中..." });

  const { data: resp } = await uni.request({
    url: `http://127.0.0.1:3000/trades/${id}`,
    method: "GET",
  });

  // 赋值
  Object.assign(model, resp);

  uni.hideLoading();
};

/** 选择交易地址 */
const onChooseLocation = async () => {
  const location = await uni.chooseLocation();
  model.address = location.address;
  model.lat = location.latitude;
  model.lng = location.longitude;
};

/** 确认修改 */
const handleConfirm = async () => {
  // 1. 触发表单校验
  await myForm.value.validate();

  // 2. 调用接口
  uni
    .request({
      url: `http://127.0.0.1:3000/trades/${model.id}`,
      method: "PUT",
      data: model,
    })
    .then(() => {
      uni.showToast({ title: "更新成功" });

      setTimeout(() => {
        // 根据当前是否有历史记录，来控制是 后退 还是 重定向
        const pages = getCurrentPages();
        if (pages.length === 1) {
          // uni.redirectTo({ url: "/pages/info/info?id=1" });
          uni.redirectTo({ url: "/pages/index/index" });
        } else {
          // 获取到 eventChannel
          const eventChannel = ctx.getOpenerEventChannel();
          // 触发 上一个页面定义上的 refresh 时间
          eventChannel.emit("refresh", model.id);
          // 后退
          uni.navigateBack();
        }
      }, 1500);
    });
};

onLoad((query) => {
  const { id } = query as { id: string };
  // 获取数据
  refresh(id);
});
</script>

<style lang="scss">
.uni-forms-item__content {
  display: flex;
  align-items: center;
  padding-right: 12px;

  input {
    width: 100%;
  }
}
</style>
